package java_thinking.unit_18_IO._18_10;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Desc:   通道间的复制
 * @author: cww
 * @DateTime: 2019/5/17 8:49
 */

public class ChannelCopy {
    private static final int BSIZE = 1024;
    private static String file = "src/maindemo/java/java_thinking/unit_18_IO/_18_10/GetChannel.txt";
    private static String file1 = "src/maindemo/java/java_thinking/unit_18_IO/_18_10/GetChannel1.txt";
    public static void main(String[] args) throws IOException {
        FileChannel in = new FileInputStream(file).getChannel(),
        out = new FileOutputStream(file1).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        //表示达到了末尾
        while (in.read(buffer) != -1) {
            //每次读入到缓冲器后flip()，以便可以被.write(buffer)
            buffer.flip();
            out.write(buffer);
            //读取后信息任然在缓冲器中，接着clear()操作则对所有内部指正重新安排，以便缓冲器在另一个read()操作期间能够做好接受
            // 数据的准备，可以使用transferTo()和transferFrom()替代
            buffer.clear();
        }
    }
}
